package com.zlp.config;

import com.zlp.security.handler.MyAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private MyAccessDeniedHandler accessDeniedHandler;

    @Autowired
    private PersistentTokenRepository persistentTokenRepository;

    /**
     * 认证管理器配置
     *
     * @param auth
     * @date: 2021/3/11 17:39
     * @return: void
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        // 设置自定义的userDetailsService
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder());
    }

    /**
     * 密码加密
     *
     * @date: 2021/3/27 18:31
     * @return: org.springframework.security.crypto.password.PasswordEncoder
     */
    @Bean
    public PasswordEncoder passwordEncoder() {

        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 配置请求地址的权限
        http.authorizeRequests()
                // 所有用户可访问,不需要登入
                .antMatchers("/test/echo").permitAll()
                // 设置前端页面
                .antMatchers("/login.html", "/error.html").permitAll()
                // 需要 ADMIN 权限
//                .antMatchers("/test/admin","/test/getUserInfo").hasAuthority("ADMIN")
                // 需要 ROLE_abc 角色，要去掉ROLE_前缀，不然会报错，SpringSecurity会自动拼接ROLE_前缀
                .antMatchers("/test/admin", "/test/getUserInfo").hasRole("abc")
                // 需要 NORMAL 权限
                .antMatchers("/test/normal", "/test/getUserInfo").hasAuthority("NORMAL") // 需要 NORMAL 角色。
                // 任何请求，访问的用户都需要经过认证
                .anyRequest().authenticated();

        //异常处理
        http.exceptionHandling()
                .accessDeniedHandler(accessDeniedHandler);
        // 设置 Form 表单登陆
        http.formLogin()
                //自定义登录页面
                .loginPage("/showLogin")
                //必须和表单提交的接口一样，会去执行自定义登录逻辑
                .loginProcessingUrl("/login")
                //登录成功后跳转页面，POST请求
                .successForwardUrl("/toMain")
                //登录失败后跳转页面，POST请求
                .failureForwardUrl("/toError")
                .permitAll();

        //退出
        http.logout()
                .logoutUrl("/logout")
                //退出成功后跳转的页面
                .logoutSuccessUrl("/login.html");

        http.rememberMe()
                //失效时间，单位秒
                .tokenValiditySeconds(600)
                //登录逻辑交给哪个对象
                .userDetailsService(userDetailsService)
                // 持久层对象
                .tokenRepository(persistentTokenRepository);

        // 禁止跨域
        http.csrf().disable();
    }
}
